package se.topshelf.golftracker.web.controller.teebox;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import se.topshelf.golftracker.core.domain.Course;
import se.topshelf.golftracker.core.domain.TeeBox;
import se.topshelf.golftracker.core.service.BaseService;
import se.topshelf.golftracker.web.validator.BaseEntityValidator;

import java.text.MessageFormat;

/**
 *  Validates TeeBox entities, so that they are ok save.
 */
public class TeeBoxValidator extends BaseEntityValidator<TeeBox> {
    public static final String HOLE_FIELD_NAME = "hole";
    public static final String LENGTH_FIELD_NAME = "length";
    public static final String TEE_COLOUR_FIELD_NAME = "teeColour";
    private BaseService baseService;


    public TeeBoxValidator(BaseService baseService) {
        super(TeeBox.class);
        this.baseService = baseService;
    }


    @Override
    protected void validateFields(TeeBox entityToCheck, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, TEE_COLOUR_FIELD_NAME, REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, LENGTH_FIELD_NAME, REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, HOLE_FIELD_NAME, REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
    }

    @Override
    protected BaseService getBaseService() {
        return baseService;
    }

    @Override
    protected boolean isNaturalKeyEqual(TeeBox savedEntity, TeeBox entityToCheck) {
        //If any combination matches
        // ToDo Narrow down the set to look in by override getPresentComparableEntities fetching only holes that are on
        // the same Course as the entityToCheck
        return savedEntity.getHole().getCourse().equals(entityToCheck.getHole().getCourse()) &&
                savedEntity.getHole().equals(entityToCheck.getHole()) &&
                savedEntity.getTeeColour().equals(entityToCheck.getTeeColour());
    }

    @Override
    protected void doRejectOfNaturalField(Errors errors, TeeBox entityToCheck) {
        errors.rejectValue(TEE_COLOUR_FIELD_NAME, "duplicate",
                MessageFormat.format("Duplicate tee box colour ",
                        entityToCheck.getTeeColour()));
    }
}
